import { Flex, Spin } from 'antd';
import '../work-modal/work.scss';
import { useEffect, useRef, useState } from 'react';

import { GetWorkBenhList } from '@/common';
import NotData from '../NotData';
import { formatData, formatDataNoTime } from '@/utils/time';
import { SvgIcon } from '../icon';
import bgPrcture from '@/assets/images/background/bg-prcture.png';
import bgLayer from '@/assets/images/background/bg-layer.png';
import workbenchService from '@/api/services/workbenchService';
import AvatarDisplay from '../work-modal/components/AvatarDisplay';
import GradientBox from '../GradientBox';
interface AppItem {
  id: string;
  name?: string;
  description?: string;
  icon?: React.ReactNode;
}
interface pageType {
  page: number;
  page_size: number;
  searchText: string;
  app_type: string | null;
  app_workbench_type: string | null;
  app_status: string | null;
  offset: number;
}

interface BoxInfoProps {
  key?: number;
  appType: string | null; //应用类型
  searchText: string; //搜索框内容
  onType?: string; // market,public,manager,fusion
  paramsType?: string | null; // market,public,manager,fusion  可支持组合用,分隔
  isMultiSelect?: number; //是否多选  0 模板 1单选 2多选
  isShowBlank?: boolean; //是否显示空白模板
  showTitle?: string; //空白模板标题
  appStatus?: string | null; //审核状态
  onToAssistant?: (e: React.MouseEvent, obj: GetWorkBenhList) => void;
  onChangeToPage?: (data: number) => void;
  confirm?: (data: GetWorkBenhList[]) => void; // 多选的情况下调用
  selectApps?: AppItem[]; // 选中情况下传入的选中数据
}

export default function BoxInfo({
  key,
  onType = '',
  paramsType = null,
  appType = 'agent',
  showTitle,
  isMultiSelect = 0,
  isShowBlank = false,
  searchText = '',
  appStatus = null,
  selectApps = [],
  onToAssistant = () => {},
  onChangeToPage = () => {},
  confirm = () => {},
}: BoxInfoProps) {
  const workAllRef = useRef<HTMLDivElement>(null);
  const [dataList, setDataList] = useState<GetWorkBenhList[]>([]);
  const [activeIndex, setActiveIndex] = useState<number>(-1);
  const [defaultPage, setDefaultPage] = useState<pageType>({
    page: 1,
    page_size: 20,
    searchText: searchText,
    app_type: appType, //应用类型
    app_workbench_type: paramsType, //应用模板类型
    app_status: appStatus, //审核状态
    offset: 0,
  });
  const [isNoData, setIsNoData] = useState<boolean>(true);
  const [isHaveData, setIsHaveData] = useState<boolean>(true);
  const [total, setTotal] = useState<number>(0);
  const [flag, setflag] = useState<boolean>(false); // 用于防止多次触发
  const baseStyle: React.CSSProperties = {
    height: 238,
    borderRadius: 12,
    // background: `url(${bgLayer}) no-repeat center top`,
    background: '#FEFFFF',
    // backgroundSize: '50% 50%',
    // border: '1px solid #ffffffe3',
    cursor: 'pointer',
    position: 'relative',
    flexShrink: 0,
  };
  const [selectedItems, setSelectedItems] = useState<GetWorkBenhList[]>([]);
  const [processedPreselectedIds, setProcessedPreselectedIds] = useState<Set<string>>(new Set());
  const [isInitialized, setIsInitialized] = useState(false);

  // 处理预选数据的核心函数
  const processPreselectedItems = (newData: any[]) => {
    if (selectApps.length === 0 || processedPreselectedIds.size >= selectApps.length) {
      return newData;
    }

    const unprocessedIds = selectApps
      .map((item) => item.id)
      .filter((id) => !processedPreselectedIds.has(id));

    const newPreselectedItems = newData.filter((item) => unprocessedIds.includes(item.app_id));

    if (newPreselectedItems.length === 0) return newData;

    const newProcessedIds = new Set(processedPreselectedIds);
    newPreselectedItems.forEach((item) => newProcessedIds.add(item.app_id));
    setProcessedPreselectedIds(newProcessedIds);

    setSelectedItems((prev) => [
      ...prev,
      ...newPreselectedItems.filter((p) => !prev.some((item) => item.app_id === p.app_id)),
    ]);

    return newData.map((item) => {
      const isPreselected = newPreselectedItems.some((p) => p.app_id === item.app_id);
      return isPreselected ? { ...item } : item;
    });
  };

  // 获取数据并处理预选
  const getPublic = async () => {
    // console.log(selectedItems, 'selectedItems');
    // console.log(dataList, 'dataList');

    try {
      const res = await workbenchService.workListApi(defaultPage);
      setIsNoData(true);
      let newData = [...dataList, ...res.app_list];
      // newData = processPreselectedItems(newData);
      const datas = newData.map((item) => {
        return {
          ...item,
          checked: selectedItems.some((selectedItem) => selectedItem.app_id === item.app_id),
        };
      });

      setDataList(datas);
      setIsHaveData(newData.length > 0);
      setflag(false);
      setTotal(res.total);

      if (!isInitialized) setIsInitialized(true);
    } catch (error) {
      console.log(error);
    }
  };

  // 处理选择操作
  const confirmOk = (obj: GetWorkBenhList) => {
    // 新增：检查是否处于锁定状态
    const isLocked = isMultiSelect === 2 && selectApps.some((app) => app.id === obj.app_id);

    // 如果是锁定状态且当前是选中状态，则禁止操作
    if (isLocked) {
      return;
    }

    if (isMultiSelect === 0) return;

    setDataList((prevData) => {
      return prevData.map((item) => {
        if (item.app_id !== obj.app_id) {
          if (isMultiSelect === 1) {
            return { ...item, checked: false };
          }
          return item;
        }
        return { ...item, checked: !item.checked };
      });
    });

    setSelectedItems((prev) => {
      if (isMultiSelect === 1) {
        return obj.checked ? [] : [obj];
      } else {
        const exists = prev.some((item) => item.app_id === obj.app_id);
        if (exists) {
          return prev.filter((item) => item.app_id !== obj.app_id);
        } else {
          return [...prev, obj];
        }
      }
    });
  };

  // 提交最终选择
  useEffect(() => {
    if (isInitialized) {
      confirm(selectedItems);
    }
  }, [selectedItems, isInitialized]);

  useEffect(() => {
    if (dataList.length > 0 && !isInitialized && selectApps.length > 0) {
      const updatedData = processPreselectedItems(dataList);
      setDataList(updatedData);
      setIsInitialized(true);
    }
  }, [dataList, isInitialized, selectApps]);

  useEffect(() => {
    getPublic();
  }, [defaultPage, key]);

  //搜索框
  useEffect(() => {
    if (defaultPage.searchText !== searchText) {
      setDataList([]);
      setDefaultPage((prev) => ({ ...prev, searchText, page: 1, offset: 0 }));
    }
  }, [searchText]);

  useEffect(() => {
    setIsNoData(false);
  }, []);

  //下拉触底操作
  const Scroll = () => {
    if (workAllRef.current) {
      let height1 = workAllRef.current.clientHeight; // 可以得到我们设置的高度 (不包括滚动的高度)
      let height2 = workAllRef.current.scrollTop; // 当滚动时被卷去的高度
      let height3 = workAllRef.current.scrollHeight; // 全部的高度 包括滚动的高度
      if (height1 + height2 + 20 > height3 && !flag) {
        // 当距离底部20 则会触发
        // 加了flag 是为了防止反复触发
        setflag(true);
        //这里进行请求
        if (dataList.length < total) {
          setDefaultPage((prev) => ({
            ...prev,
            page: defaultPage.page + 1,
            offset: defaultPage.page * defaultPage.page_size,
          }));
        }
      }
    }
  };

  function mouseEvent(e: number) {
    return () => {
      setActiveIndex(e);
    };
  }

  function mouseLeave() {
    return () => {
      setActiveIndex(-1);
    };
  }

  return (
    <div>
      <div
        ref={workAllRef}
        onScroll={Scroll}
        className="flex h-[500px] min-w-[290px] flex-1 flex-col overflow-auto px-2"
      >
        {!isNoData ? (
          <Flex align="center" gap="middle" className="flex h-full items-center justify-center">
            <Spin size="large" />
          </Flex>
        ) : (
          <>
            <Flex className="grid-module">
              {isShowBlank && (
                <div
                  onClick={() =>
                    onChangeToPage(
                      showTitle == '创建智能体' ? 1 : showTitle == '创建工作流' ? 2 : 3,
                    )
                  }
                  style={{ border: '2px solid #F8FAFB' }}
                  className="jr-step-v2-2 jr2-step-v2-1 create-agent max-w-[300px]"
                >
                  <SvgIcon icon="work-add" size={30} />
                  <div className="word-color  mt-2 text-sm ">
                    {showTitle == '创建智能体'
                      ? '从零创建智能体'
                      : showTitle == '创建工作流'
                      ? '从零创建工作流'
                      : '从零创建融合应用'}
                  </div>
                </div>
              )}
              {Array.from(dataList).map((item: any, i) => (
                <GradientBox
                  key={item.app_id}
                  active={item.checked}
                  style={{ ...baseStyle }}
                  className={`boxs w-[300px] bg-[#ffffff] !shadow-none ${
                    isMultiSelect === 2 && selectApps.some((app) => app.id === item.app_id)
                      ? '!cursor-no-drop !border-none !shadow-none'
                      : 'box-hover'
                  }`}
                  onMouseEnter={mouseEvent(i)}
                  onMouseLeave={mouseLeave()}
                  onClick={() => {
                    confirmOk(item);
                  }}
                >
                  {isMultiSelect === 2 && selectApps.some((app) => app.id === item.app_id) && (
                    <div className="absolute right-0 top-0 z-10 rounded-bl-2xl rounded-tr-[10px] bg-functional-green px-3 py-1 text-center text-xs text-grays">
                      已添加
                    </div>
                  )}
                  <div
                    style={{
                      background: `url(${bgLayer}) no-repeat #FFF center top`,
                      backgroundSize: '50% 100%',
                    }}
                    className="absolute left-0 top-0 flex h-[116px] w-full justify-center rounded-xl pt-4"
                  >
                    <div>
                      <AvatarDisplay src={item.app_logo} size={50} className="h-[56px] w-[56px]" />
                    </div>
                  </div>
                  <div
                    className="relative z-10  mt-[66px] px-5 pt-5 backdrop-blur-sm"
                    style={{
                      borderTop: '1px solid transparent',
                      backgroundImage:
                        'linear-gradient(270deg, rgba(255, 255, 255, 0.04) 0%, #FFFFFF 50%, rgba(255, 255, 255, 0.04) 100%), linear-gradient(270deg, rgba(0, 0, 0, 0.04) 0%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0.04) 100%)',
                      backgroundOrigin: 'border-box',
                      backgroundClip: 'border-box',
                      backgroundSize: '100% 1px, 100% 1px',
                      backgroundPosition: 'top left',
                      backgroundRepeat: 'no-repeat',
                      // border: '1px solid green',
                      width: '99%',
                    }}
                  >
                    <div className="w-[95%] min-w-[50px] truncate text-base font-bold">
                      {item.app_name}
                    </div>
                    <div className=" mb-4 mt-2 flex items-center justify-between text-xs text-[#074B79]">
                      <div
                        className=" h-[18px] rounded-small px-[6px] text-xs leading-[18px]"
                        style={
                          item.app_type == 'agent'
                            ? { background: '#C0F8EF', color: '#00454D' }
                            : item.app_type == 'workflow'
                            ? { background: '#E3C7FD', color: '#280976' }
                            : { background: '#BADEFF', color: '#002379' }
                        }
                      >
                        {item.app_type == 'agent'
                          ? '智能体'
                          : item.app_type == 'workflow'
                          ? '工作流'
                          : '融合应用'}
                      </div>
                      <div className="flex h-5 w-2/4 justify-end text-xs">
                        <span className="mt-[1px] whitespace-nowrap text-[#C9CDD4]">By</span>
                        <div className="ml-2 flex max-w-[12em] items-center text-text-3">
                          <div className="max-w-[6em] truncate">{item.group_name}</div>
                          <div className=" whitespace-nowrap">/</div>
                          <div className="max-w-[6em] truncate"> {item.user_name}</div>
                        </div>
                      </div>
                    </div>
                    <div className=" line-clamp-2 h-9 overflow-hidden  text-ellipsis  text-sm text-[#4E5969]">
                      <div className="text text-xs">
                        {item.review_status === 'reject' && '驳回原因:'}
                      </div>
                      {item.review_status === 'reject'
                        ? item.review_description
                        : item.app_description}
                    </div>
                  </div>
                  <div className=" flex h-10 items-center justify-between rounded-bl-xl rounded-br-xl bg-[#FEFFFF] px-5 ">
                    <div className=" text-xs text-text-3">
                      {formatDataNoTime(item.create_time)}
                      <span className="ml-1">更新</span>
                    </div>
                  </div>
                  {/* 针对模块创建的浮窗 */}
                  {onType === 'market' && (
                    <div className="popup-content">
                      <div
                        className="popup-content-child"
                        onClick={(e) => {
                          onToAssistant(e, item);
                        }}
                      >
                        应用该模板
                      </div>
                    </div>
                  )}
                </GradientBox>
              ))}
            </Flex>
            {dataList.length <= 0 && <NotData iconSize={80} textClassName={'text-sm'} />}
          </>
        )}
      </div>
    </div>
  );
}
